package com.example.emos.api.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaMode;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.example.emos.api.common.util.PageUtils;
import com.example.emos.api.common.util.R;
import com.example.emos.api.controller.form.*;
import com.example.emos.api.db.dao.TbExamDao;
import com.example.emos.api.db.dao.TbMarkDao;
import com.example.emos.api.db.pojo.TbExam;
import com.example.emos.api.service.ExamService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

/**
 * @author ：Supyo
 * @date ：Created in 2021/11/13 22:22
 * @description：评分考核
 */
@RestController
@RequestMapping("/checkList")
@Tag(name = "ExamController", description = "评分考核接口")
@Slf4j
public class ExamController {
    @Autowired
    TbMarkDao markDao;

    @Autowired
    private ExamService examService;

    @Autowired
    private TbExamDao examDao;

    @PostMapping("/selectCheckListById")
    @Operation(summary = "根据Id查询评分考核")
    public R selectCheckListById(@Validated @RequestBody SelectCheckListByIdForm form) {
        TbExam exam = examService.selectCheckListById(form.getId());
        return R.ok().put("list", exam);
    }


    @PostMapping("/selectCheckListBypages")
    @Operation(summary = "分页查询评分考核")
    public R selectCheckListBypages(@Validated @RequestBody SelectCheckListBypagesForm form) {
        int page = form.getPage();
        int length = form.getLength();
        int start = (page - 1) * length;
        HashMap param = JSONUtil.parse(form).toBean(HashMap.class);
        param.put("start", start);
        PageUtils pageUtils = examService.selectCheckListBypagesForm(param);
        return R.ok().put("page", pageUtils);
    }


    @PostMapping("/addMark")
    @Operation(summary = "添加考核")
    @SaCheckPermission(value = {"ROOT", "HR"}, mode = SaMode.OR)
    public R insert(@Valid @RequestBody InsertExamForm form) throws ParseException {
        TbExam exam = JSONUtil.parse(form).toBean(TbExam.class);
        exam.setTitle(form.getTitle());

        //根据时间设置考核状态
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date time = new Date();
        Date startTime = formatter.parse(form.getStart_time());
        Date endTime = formatter.parse(form.getEnd_time());
        int status = 2;
        if (time.after(startTime) && time.before(endTime)) {
            status = 2;
        }
        if (time.before(startTime)) {
            status = 1;
        }
        if (time.after(endTime)) {
            status = 3;
        }
        exam.setStatus((byte) status);

        exam.setPerson(JSONUtil.parseArray(form.getPerson()).toString());
        exam.setScorer(JSONUtil.parseArray(form.getScorer()).toString());
        exam.setWeight(JSONUtil.parseArray(form.getWeight()).toString());
        exam.setCreateTime(new Date());
        int rows = examService.insert(exam);

        //先把person的id提取出来
        String a = JSONUtil.parseArray(form.getPerson()).toString();
        JSONArray jsonArray = null;
        jsonArray = new JSONArray(a);
        int person[] = new int[jsonArray.size()];
        for (int i = 0; i < jsonArray.size(); i++) {
            person[i] = (int) jsonArray.getJSONObject(i).get("id");
            System.out.println("person的id: " + person[i]);
        }
        //先把person的name提取出来
        String personName = JSONUtil.parseArray(form.getPerson()).toString();
        JSONArray NamejsonArray = null;
        NamejsonArray = new JSONArray(personName);
        String name[] = new String[NamejsonArray.size()];
        for (int i = 0; i < NamejsonArray.size(); i++) {
            name[i] = (String) NamejsonArray.getJSONObject(i).get("name");
            System.out.println("person的name: " + name[i]);
        }


        //把scorer的id提取出来
        String b = JSONUtil.parseArray(form.getScorer()).toString();
        JSONArray jsonArrayb = null;
        jsonArrayb = new JSONArray(b);
        int scorer[] = new int[jsonArrayb.size()];
        for (int i = 0; i < jsonArrayb.size(); i++) {
            scorer[i] = (int) jsonArrayb.getJSONObject(i).get("id");
            System.out.println("scorer的id: " + scorer[i]);
        }
        //把scorer的weight提取出来
        int[] weight = new int[form.getWeight().length];
        for (int i = 0; i < weight.length; i++) {
            weight[i] = form.getWeight()[i];
            System.out.println("weight: " + weight[i]);
        }


        //根据person数量-新增被考核条数
        int maxExamineeId = 0;
        if (person.length > 0) {
            for (int i = 0; i < person.length; i++) {
                maxExamineeId = examDao.maxExamineeId() + 1;
                examDao.insertExaminee(maxExamineeId, person[i], name[i]);
            }
        }

        //根据person数量和scorer数量和weight-新增考核条数
        //新增考核任务
        int templateId = form.getExamTemplateId();


        //根据考核模板Id查询试卷
        Object options = markDao.paper(templateId);
        int maxExamId = examDao.maxExamId();
        double totalScore = examDao.totalScore(templateId);


        int countMark = scorer.length + person.length;
        for (int i = 0; i < scorer.length; i++) {
            for (int j = 0; j < person.length; j++) {
                int markId = examDao.markId();
                int markID = markId + 1;
                String scoreName[] = new String[scorer.length];
                scoreName[i] = markDao.selectPersonName(scorer[i]);
                int maxExamineeId1 = maxExamineeId + j + 1 - person.length;
                //Mark表新增
                examDao.addmark(person[j], name[j], scorer[i], weight[i], maxExamineeId1);
                //Task表新增
                examDao.insertTask(
                        form.getTitle(),
                        person[j],
                        name[j],
                        scorer[i],
                        scoreName[i],
                        options, maxExamId,
                        totalScore,
                        markID);
            }
        }

        return R.ok().put("rows", rows);
    }


    @PostMapping("/deleteMark")
    @Operation(summary = "删除考核记录")
    @SaCheckPermission(value = {"ROOT", "HR"}, mode = SaMode.OR)
    public R deleteMark(@Valid @RequestBody DeleteExamForm form) {
        int rows = examService.deleteExamByIds(form.getIds());
        return R.ok().put("rows", rows);
    }

    @PostMapping("/updateMark")
    @Operation(summary = "修改考核")
    @SaCheckPermission(value = {"ROOT", "HR"}, mode = SaMode.OR)
    public R update(@Valid @RequestBody UpdateExamForm form) {
        HashMap param = JSONUtil.parse(form).toBean(HashMap.class);
        param.replace("person", JSONUtil.parseArray(form.getPerson()).toString());
        param.replace("scorer", JSONUtil.parseArray(form.getScorer()).toString());
        param.replace("weight", JSONUtil.parseArray(form.getWeight()).toString());
        int rows = examService.update(param);
        return R.ok().put("rows", rows);
    }

    @GetMapping("/getUser")
    @Operation(summary = "获取没有离职的用户")
    public R getUser() {
        ArrayList<HashMap> data = new ArrayList<HashMap>();
        data = examService.getUser();
        return R.ok().put("data", data);
    }
}
